package com.hui.stock.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hui.stock.mapper.SysPermissionMapper;
import com.hui.stock.mapper.SysRoleMapper;
import com.hui.stock.mapper.SysRolePermissionMapper;
import com.hui.stock.pojo.domain.MenuDomain;
import com.hui.stock.pojo.entity.SysPermission;
import com.hui.stock.pojo.entity.SysRole;
import com.hui.stock.pojo.entity.SysRolePermission;
import com.hui.stock.service.RoleService;
import com.hui.stock.utils.IdWorker;
import com.hui.stock.utils.UserRolePermissionUtil;
import com.hui.stock.vo.req.RolePageInfoReqVo;
import com.hui.stock.vo.req.AddRoleReqVo;
import com.hui.stock.vo.req.UpdateRoleReqVo;
import com.hui.stock.vo.resp.PageResult;
import com.hui.stock.vo.resp.R;
import com.hui.stock.vo.resp.ResponseCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: ymh
 * @date: 2024/12/30 16:05
 * @description:
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Override
    public R<PageResult> getRolePageInfo(RolePageInfoReqVo rolePageInfoReqVo) {
        //1 使用PageHelper启动分页
        PageHelper.startPage(rolePageInfoReqVo.getPageNum(), rolePageInfoReqVo.getPageSize());
        //2 调用Mapper返回分页数据
        List<SysRole> rolePageInfo = sysRoleMapper.getRolePageInfo();
        if (CollectionUtils.isEmpty(rolePageInfo)){
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        //3 组装返回页面对象,PageInfo会从线程中自动获取PageHelper的查询结果（页面，总页数，当前页....）
        PageInfo<SysRole> pageInfo = new PageInfo<>(rolePageInfo);
        PageResult<SysRole> pageResult = new PageResult<>(pageInfo);
        return R.ok(pageResult);
    }

    @Override
    public R<List<MenuDomain>> getAllPermissionsTree() {
        //获取所有权限
        List<SysPermission> permissions = sysPermissionMapper.getAllAvailablePermissions();
        //获取权限菜单
        List<MenuDomain> menuDomains = UserRolePermissionUtil.buildPermissionTree(permissions);
        return R.ok(menuDomains);
    }

    @Override
    public R addRole(AddRoleReqVo roleReqVo) {
        //1 创建新增角色信息
        //1.1 先判断角色是否被删除
        long roleId;
        SysRole role = sysRoleMapper.selectByName(roleReqVo.getName());
        if (role!=null){
            if (role.getDeleted()==1){
                return R.error("该角色已经存在！");
            }
            roleId = role.getId();
            role.setDeleted(1);
        }else {
            SysRole sysRole = new SysRole();
            roleId = idWorker.nextId();
            sysRole.setId(roleId);
            sysRole.setName(roleReqVo.getName());
            sysRole.setDescription(roleReqVo.getDescription());
            sysRole.setStatus(1);
            sysRole.setDeleted(1);
            sysRole.setCreateTime(new Date());
            //2 调用mapper新增角色信息
            int insert = sysRoleMapper.insert(sysRole);
            if (insert<0){
                return R.error("角色新增失败！");
            }
        }
        //3 创建用户角色列表
        Date date = new Date();
        List<SysRolePermission> sysRolePermissions = new ArrayList<>();
        roleReqVo.getPermissionsIds().forEach(permissionId->{
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setId(idWorker.nextId());
            sysRolePermission.setRoleId(roleId);
            sysRolePermission.setPermissionId(permissionId);
            sysRolePermission.setCreateTime(date);
            sysRolePermissions.add(sysRolePermission);
        });
        //4 调用mapper新增角色权限信息
        int insert1 = sysRolePermissionMapper.batchInsert(sysRolePermissions);
        if (insert1<0){
            return R.error("角色权限新增失败！");
        }
        return R.ok("操作成功！");
    }

    @Override
    public R<List<Long>> getRolePermissions(Long roleId) {
        List<Long> list = sysRolePermissionMapper.getPermissionIds(roleId);
        return R.ok(list);
    }

    @Override
    public R updateRole(UpdateRoleReqVo updateRoleReqVo) {
        //1 更新角色表信息
        Date date = new Date();
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(updateRoleReqVo,sysRole);
        sysRole.setUpdateTime(date);
        sysRoleMapper.updateByPrimaryKeySelective(sysRole);
        //2 删除角色权限表信息
        sysRolePermissionMapper.deleteByPrimaryKey(updateRoleReqVo.getId());
        //3 创建用户角色列表
        List<SysRolePermission> sysRolePermissions = new ArrayList<>();
        updateRoleReqVo.getPermissionsIds().forEach(permissionId->{
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setId(idWorker.nextId());
            sysRolePermission.setRoleId(updateRoleReqVo.getId());
            sysRolePermission.setPermissionId(permissionId);
            sysRolePermission.setCreateTime(date);
            sysRolePermissions.add(sysRolePermission);
        });
        //4 调用mapper新增角色权限信息
        int insert1 = sysRolePermissionMapper.batchInsert(sysRolePermissions);
        if (insert1<0){
            return R.error("角色权限新增失败！");
        }
        return R.ok("操作成功！");
    }

    @Override
    public R<List<Long>> deleteRoleAndPermissions(Long roleId) {
        //1 删除角色
        SysRole sysRole = new SysRole();
        sysRole.setId(roleId);
        sysRole.setDeleted(0);
        sysRole.setUpdateTime(new Date());
        sysRoleMapper.updateByPrimaryKeySelective(sysRole);
        //删除角色相关权限
        sysRolePermissionMapper.deleteByRoleId(roleId);
        return R.ok("删除角色及其权限成功");
    }

    @Override
    public R updateRoleStatus(Long roleId, Integer status) {
        SysRole sysRole = new SysRole();
        sysRole.setId(roleId);
        sysRole.setStatus(status);
        sysRoleMapper.updateByPrimaryKeySelective(sysRole);
        return R.ok("操作成功！");
    }
}
